package com.chenshu.vialate;

import com.chenshu.Obj;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.logging.Filter;

/**
 * Created with IntelliJ IDEA
 * Description
 * User：chenshu
 * Date：2024-03-27
 * Time：20:41
 */
public class CreateInstance {
    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, ClassNotFoundException, NoSuchFieldException {
        Class userClazz = Class.forName("com.chenshu.vialate.User");
        //获取私有构造器
        Constructor declaredConstructor = userClazz.getDeclaredConstructor(int.class, String.class);
        //暴破，使用反射可以访问private构造器
        declaredConstructor.setAccessible(true);
        Object user = declaredConstructor.newInstance(20, "zhangsan");
        System.out.println(user);

        Field age  =userClazz.getDeclaredField("age");
        age.setAccessible(true);
        age.set(user, 99);
        System.out.println(user);

        Method method = userClazz.getDeclaredMethod("userMethod");
        method.setAccessible(true);
        method.invoke(user);
    }
}

class User {
    private int age;
    private String name;

    @Override
    public String toString() {
        return "User{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }

    private User(int age, String name) {
        this.age = age;
        this.name = name;
    }

    private void userMethod() {
        System.out.println("this is a private method..");
    }
}
